package tank.bullet;

import frame.GameFrame;
import gameBasics.*;
import tank.Dir;
import java.awt.*;
import java.util.Objects;

public class Bullet extends GameObject {

    private final BulletGroup bulletGroup;          //炮弹所属阵营
    public static final int WIDTH = ResourceManager.bulletNormal.getWidth();   //炮弹的宽度
    public static final int HEIGHT = ResourceManager.bulletNormal.getHeight(); //炮弹的高度
    private final Dir dir;                          //炮弹运动方向
    private static final int SPEED = Objects.requireNonNull(PropertyManager.getInt("bulletSpeed"));   //坦克速度
    private boolean livingState = true;             //子弹存活状态

    //有参构造方法
    public Bullet(BulletGroup bulletGroup, int x, int y, Dir dir){
        this.bulletGroup = bulletGroup;
        this.x = x;
        this.y = y;
        this.dir = dir;

        rectangle.x = this.x;
        rectangle.y = this.y;
        rectangle.width = WIDTH;
        rectangle.height = HEIGHT;

        GameModel.getInstance().addGameObject(this);
    }

    public BulletGroup getBulletGroup() {
        return bulletGroup;
    }

    /**
     * 绘制炮弹
     * @param graphics 画笔对象
     */
    public void paint(Graphics graphics){
        if(!livingState) GameModel.getInstance().removeGameObject(this);

        graphics.drawImage(ResourceManager.bulletNormal,x,y,null);
        
        move();
    }

    @Override
    public int getWidth() {
        return WIDTH;
    }

    @Override
    public int getHeight() {
        return HEIGHT;
    }

    /**
     * 炮弹移动
     */
    private void move() {
        switch (dir) {
            case LEFT -> x -= SPEED;
            case UP -> y -= SPEED;
            case RIGHT -> x += SPEED;
            case DOWN -> y += SPEED;
        }

        //更新炮弹的rectangle
        rectangle.x = this.x;
        rectangle.y = this.y;

        if(x < 0 || y < 0 || x > GameFrame.GAME_WIDTH || y > GameFrame.GAME_HEIGHT) livingState = false;
    }

    /**
     * 炮弹消亡
     */
    public void die() {
        this.livingState = false;
    }

}